let _animation;
let _elem;
let _arrowX
let _arrowY


export const initArrow = (elem, x, y) => {
  _elem = elem
  _arrowX = x
  _arrowY = y
}

// 计算圆周射击点相对坐标
const getFiringPoint = (deg) => {
  const degPai = deg * Math.PI / 180
  // 子弹起始位置距离圆心的距离
  // 屏幕半径
  const R = 233;
  const L = _arrowY - R;
  const D = L * Math.cos(degPai) + Math.sqrt(Math.pow(R, 2) - Math.pow(L * Math.sin(degPai), 2))
  const x = D * Math.cos(Math.PI / 2 - degPai);
  const y = D * Math.sin(Math.PI / 2 - degPai);
  return [x, y]
}



/* 
  计算是否命中射击目标
  使用到解析几何中，直线的一般表达式求解，点到直线距离计算。

  已知直线上的两点P1(X1,Y1) P2(X2,Y2)， P1 P2两点不重合。则直线的一般式方程AX+BY+C=0中，A B C分别等于：
  A = Y2 - Y1
  B = X1 - X2
  C = X2*Y1 - X1*Y2

  点到直线的距离公式：
  |AX0 + By0 + C|
  ----------------
  √A^2 + B^2
*/
const isHitTarget = (targetX, targetY, targetR, landedX, landedY, arrowX, arrowY) => {
  const A = landedY - arrowY
  const B = arrowX - landedX
  const C = landedX * arrowY - arrowX * landedY
  const d = Math.abs(A * targetX + B * targetY + C) / Math.sqrt(Math.pow(A, 2) + Math.pow(B, 2))
  return d <= targetR / 2;
}

export const sendBullet = (deg, target, beforecb, cb) => {
  const [dx, dy] = getFiringPoint(-deg)
  const isHit = isHitTarget(target.x, target.y, target.size, _arrowX - dx, _arrowY - dy, _arrowX, _arrowY);
  beforecb(isHit)
  // console.log({ isHit })
  const keyframes = [
    {
      transformOrigin: "50% 50%",
      time: 0,
      transform: {
        translateY: 0,
        translateX: 0,
      },
    },
    {
      transformOrigin: "50% 50%",
      time: 100,
      transform: {
        translateY: -dy,
        translateX: -dx,
      },
    }
  ]
  const options = {
    duration: 500,
    easing: 'linear',
    delay: 0,
    // fill: 'forwards'
  }
  _animation = _elem.animate(keyframes, options)
  _animation.play()
  _animation.onfinish = () => {
    cb(isHit)
  }
}